

var SignCtrl = function()
{

    function CtrlImpl()
    {}
    
    CtrlImpl.sign = function(relative, data, certSN, ajaxOption)
    {
    	data += "&certSN=" + certSN;
    	
        //首先获取摘要
        $.ajax({
            url : relative + "quick-ukey!ukeyPdfHash.xml",
            type : "POST",
            data : data,
            dataType : "xml",
            timeout : 300000,
            error : function()
            {},
            success : function(data) 
            {
                //摘要获取后使用控件对其签名
                var result = checkStream($(data).find("result >resultMsg").text());
                if (null == result) 
                {
                    return;
                }
                
                //得到摘要,使用签名控件进行签名
                ukeySign(relative, result.hash, certSN, ajaxOption);
            }
        });
    }; 
    
    
    CtrlImpl.signHash = function(relative, hash, certSN, ajaxOption)
    {
        ukeySign(relative, hash, certSN, ajaxOption);
    };
    CtrlImpl.testUkeyCtrl = function(certSN){
        var ctrlId = createCtrl();
        var ctrl = getUkeyObject(ctrlId);
        if (null == ctrl)
        {
            //控件未加载
            closeAlert();
            showDownload(relative);
            return false;
        }

        var cert = getCert(ctrl, certSN);
        if (null == cert || 0 == cert.length)
        {
            closeAlert();
            showAlert("证书不存在,请检查是否已插入Ukey。");
            return false;
        }
        return true;
    }
    function ukeySign(relative, hash, certSN, ajaxOption)
    {
        var ctrlId = createCtrl();

        var ctrl = getUkeyObject(ctrlId);
        if (null == ctrl)
        {
        	//控件未加载
        	closeAlert();
        	showDownload(relative);
            return;
        }

        var cert = getCert(ctrl, certSN);
        if (null == cert || 0 == cert.length)
        {
        	closeAlert();
        	showAlert("证书不存在,请检查是否已插入Ukey。");
            return;
        }

        ukeyCtrlSign(relative, ctrl, hash, certSN, cert, ajaxOption);            
    }
    
    function showDownload(relative)
    {
    	var url = relative + "../TGESignPlugIn.exe";
    	var download = "<a href='" + url + "'>此处</a>";
    	var display = "仅支持IE浏览器，若无法正确加载控件，请点击 " + download + "下载安装证书控件 ";
    	
    	showAlert(display);
    }


    function createCtrl()
    {
        var id = "TGESignCtrl";
        var html = "";
        
        if ($("#" + id).length > 0)
        {
            return id;
        }
        
        html += "<object id='" + id + "' name='" + id + "' codebase='../TGESignCtrl.cab' classid='CLSID:08E2ACF2-E1E8-4AAA-BC31-14CDE6E7FE5B' width='0' height='0'>";
        html += "<embed name='" + id + "' width='0' height='0' src=></embed>";
        html += "</object>";
        
        $("body").prepend(html);
        
        return id;
    }

	function isIEBrowser() {
		var isIE11 = (navigator.userAgent.indexOf('MSIE') > -1 && navigator.userAgent
				.indexOf('Trident') > -1)
				|| (navigator.userAgent.indexOf('Trident') > -1 && navigator.userAgent
						.indexOf('rv:11') > -1);
		if (isIE11) {
			return true;
		}

		return (navigator.appName.indexOf("Microsoft Internet") != -1);
	}

	function getPluginObjcet(objname) {
		if (!isIEBrowser()) {
			if (document.embeds && document.embeds[objname])
				return document.embeds[objname];
		} else
			return document.getElementById(objname);
	}    

    function getPluginActiveObject()
    {
        var obj;
        try
        {
            obj = new ActiveXObject("TGESignCtrl.1");
            return obj;
        }
        catch(e)
        { 
            return null;
        }
    }

    function getUkeyObject(id)
    {
        var ctrl = getPluginObjcet(id);
        if (testCtrl(ctrl))
        {
        	return ctrl;
        }
        
    	ctrl = getPluginActiveObject();
        if (testCtrl(ctrl))
        {
        	return ctrl;
        }

		return null;
    }
    
    function testCtrl(ctrl)
    {
    	if (null == ctrl)
    	{
    		return false;
    	}
    	
        //测试控件
		try 
		{
			ctrl.GetVersion();
		}
		catch (e) 
		{
			return false;
		}
		
		return true;
    }

    function getCert(ctrl, certSN) 
    {
        return ctrl.ExportUserCert(certSN, 0);
    }
            
    function ukeySignFinished(relative, hash, signature, ajaxOption)
    {
        var defaultOp = 
        {
            custom: "",
            error: function(){},
            success: function(){},
            async: true,
            notifyType: "Empty",
            pri: ""
        };
        var ops = $.extend({}, defaultOp, ajaxOption);
        
        //参数
        var data = 
    	{
        	hash: hash,
    	    signature: signature,
    	    custom: ops.custom,
    	    notifyType: ops.notifyType,
    	    //此为本系统业务数据
    	    esignJson: ops.pri
    	};
        
        //这里进行签名合并
        $.ajax({
            url : relative + "quick-ukey!onUkeyFinished2",
            type : "post",
            data : data,
            dataType : "json",
            timeout : 300000,
            async: ops.async,
            error : ops.error,
            success : ops.success
        });
    }        

    function ukeyCtrlSign(relative, ctrl, hash, certSN, cert, ajaxOption)
    {
    	var hashDecoded = decodeURIComponent(hash);
    	
    	//导入信任链
    	ctrl.ImportTrustCert(0);
    	
    	//签名
        var signature = ctrl.SignData(certSN, 1, hashDecoded);
        
        //签名验证
        var result = ctrl.VerifySignData(cert, 1, hashDecoded, signature);
        if(!result)
        {
        		closeAlert();
            alert("签名出现异常,验证失败,请联系管理员.");
            return;
        }
        
        //签名成功,通知
        ukeySignFinished(relative, hashDecoded, signature, ajaxOption);
    }        	

    return CtrlImpl;
}();





